<?php

namespace app\common\serve;

use app\common\logic\Logic;
use think\Db;
use think\Exception;

/**
 * 投资
 * Class Invest
 * @package app\common\serve
 */
class Invest extends Serve
{
    /**
     * 预付购买
     * @param $params
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function prePay($params)
    {

        $uid = $params['uid'];
        $borrow_id = $params['borrow_id'];

        $money = $params['money'] > 1 ? floor($params['money']) : 0;
        if ($money < 1) return ['code' => 0, 'msg' => '请输入正整数金额！'];
        if (!(floor($money) == $money)) return ['code' => 0, 'msg' => '请输入正整数金额！'];

        //验证 ：
        $user = Db::name('user')->where(['id' => $uid])->find();
        if (!$user) return ['code' => 0, 'msg' => '用户不存在', 'data' => ''];

        $borrow = Db::name('borrow')->where(['id' => $borrow_id])->find();
        if (!$borrow) return ['code' => 0, 'msg' => '项目不存在', 'data' => ''];

        $pre_money = $money * ($borrow['borrow_prepay_rate'] / 100);
        $invest = [
            'invest_uid' => $params['uid'],
            'borrow_id' => $borrow_id,
            'invest_capital' => $money,
            'prepay_rate' => $borrow['borrow_prepay_rate'],
            'prepay_money' => $pre_money,
            'remain_money' => $money - $pre_money,
            'way' => $params['way'],
            'ip' => $params['ip'],
            'create_time' => $_SERVER['REQUEST_TIME'],
            'status' => 1, //冻结中
            'audit_status' => 2//审核中
        ];

        Db::startTrans();

        $invest_id = Db::name('borrow_invest')->insertGetId($invest);
        $money_flag = User::memberMoneyLog($uid, 5, -$pre_money, '购买' . $borrow['borrow_name'] . ', 预付款冻结中');
        $borrow_flag = Db::name('borrow')->where(['id' => $borrow_id])->update([
            'borrow_times' => ($borrow['borrow_counts'] + 1),
            'update_time'   =>  $_SERVER['REQUEST_TIME']
        ]);

        $msg_id = Db::name('user_msg')->insertGetId(array(
            'uid' => $uid,
            'title' => '购买成功',
            'info' => '恭喜您购买预付成功, 金额' . $pre_money . '元' . '，详情请查看资金记录',
            'create_time' => $_SERVER['REQUEST_TIME']
        ));

        if ($invest_id && $borrow_flag && $money_flag && $msg_id) {
            Db::commit();

            return ['code' => 1, 'msg' => '购买预付成功，请等待财务审核.....', 'data' => ''];
        } else {
            trace('购买失败：' . json_encode($params) . '--' . $invest_id . '-' . $money_flag . '-' . $borrow_flag . '-' . $msg_id, 'error');
            return ['code' => 0, 'msg' => '购买失败', 'data' => ''];
        }
    }

    /**
     * 确定支付
     * @param $params
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function readyPay($params)
    {

        $uid = $params['uid'];
        $borrow_id = $params['borrow_id'];

//        'uid' => $this->uid,
//                    'borrow_id' => $params['borrow_id'],
//                    'money' => $params['money'],
//                    'ip' => $this->request->ip(),
//                    'way' => $this->isMobile() ? 2 : 1

        $money = $params['money'] > 1 ? floor($params['money']) : 0;
        if ($money < 1) return ['code' => 0, 'msg' => '请输入正整数金额！'];
        if (!(floor($params['money']) == $money)) return ['code' => 0, 'msg' => '请输入正整数金额！'];

        //验证 ：
        $user = Db::name('user')->where(['id' => $uid])->find();
        if (!$user) return ['code' => 0, 'msg' => '用户不存在', 'data' => ''];

        $borrow = Db::name('borrow')->where(['id' => $borrow_id])->find();
        if (!$borrow) return ['code' => 0, 'msg' => '项目不存在', 'data' => ''];

        $info = [
            'invest_uid' => $params['uid'],
            'borrow_id' => $borrow_id,
            'invest_capital' => $money,

            'way' => $params['way'],
            'ip' => $params['ip'],
            'create_time' => $_SERVER['REQUEST_TIME']

//             `invest_uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '投资人ID',
//  `borrow_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '标的ID',
//  `invest_capital` decimal(15,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '投标金额',
//  `invest_interest` decimal(15,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '产生利息',
//  `way` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '投资来源 投资来源 1PC 2手机端',
//  `status` tinyint(3) unsigned NOT NULL DEFAULT '2' COMMENT '投资状态 1成功  2失败 3还款中 4还款完成 5逾期',
//  `audit_status` tinyint(2) unsigned NOT NULL DEFAULT '0' COMMENT '审核状态',
//  `create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '投资时间',
//  `update_time` int(11) NOT NULL,
        ];

        Db::startTrans();

        $invest_id = Db::name('borrow_invest')->insertGetId($info);
        $money_flag = User::memberMoneyLog($uid, 6, -$money, "对{$borrow_id}号标进行投标");
        $borrow_flag = Db::name('borrow')->where(['id' => $borrow_id])->update([
            'has_borrow' => ['exp', 'has_borrow + ' . $money],
            'cash_borrow' => ['exp', 'cash_borrow -' . $money],
            'borrow_times' => ['exp', 'borrow_times + 1'],
        ]);

        $msg_id = Db::name('user_mag')->insertGetId(array(
            'uid' => $uid,
            'title' => '购买成功',
            'info' => '恭喜您购买成功, 购买金额' . $money . '元' . '，详情请查看资金记录',
            'create_time' => $_SERVER['REQUEST_TIME']
        ));

        if ($invest_id && $borrow_flag && $money_flag && $msg_id) {
            Db::commit();

            return ['code' => 1, 'msg' => '购买成功,请到会员中心查看', 'data' => ''];
        } else {
            trace('购买失败：' . json_encode($params) . '--' . $invest_id . '-' . $money_flag . '-' . $borrow_flag . '-' . $msg_id, 'error');
            return ['code' => 0, 'msg' => '购买失败', 'data' => ''];
        }
    }


    /**
     * 投资
     * @param array $params
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function invest($params = [])
    {
        $money = $params['money'];
        $borrow_id = $params['borrow_id'];
        $uid = $params['uid'];

        if (!(floor($money) == $money)) return ['code' => 0, 'msg' => '请输入正整数金额！'];
        if ($money < 1 || $borrow_id < 1 || $uid < 1) return ['code' => 0, 'msg' => '参数出错,请检查！'];

        $borrow_db = db('borrow');
        $mdb = db('user');

        $binfo = $borrow_db->lock(true)->field(true)->where(['id' => $borrow_id, 'borrow_status' => 2])->find();
        $user = $mdb->field(true)->where(array('id' => $uid))->find();

        if (is_null($binfo)) return ['code' => 0, 'msg' => '系统出错，找不到标的！'];
        if (is_null($user)) return ['code' => 0, 'msg' => '系统出错，找不到用户！'];

        $invest_db = db('borrow_invest');

        $investInfo = [
            'status' => 1,
            'borrow_id' => $borrow_id,
            'invest_uid' => intval($uid),
            'invest_capital' => $money,
            'invest_interest' => Logic::calcInvestInterest([
                'repayment_type' => $binfo['repayment_type'],
                'borrow_interest_rate' => $binfo['borrow_interest_rate'],
                'borrow_duration' => $binfo['borrow_duration'],
                'money' => $money
            ]),
            'create_time' => $_SERVER['REQUEST_TIME'],
            'way' => $params['way'] >= 1 ? intval($params['way']) : 1,
            'invest_days' => $binfo['remaining_time'],
            'year_rate_money' => 0,
        ];


        Db::startTrans();

        $invest_id = $invest_db->insertGetId($investInfo);
        //更新投资人账户
        $money_flag = User::memberMoneyLog($uid, 6, -$money, "对{$borrow_id}号标进行投标", $binfo['borrow_uid']);

        //更新投标进度
        $borrow_flag = $borrow_db->where(['id' => $borrow_id])->update([
            'has_borrow' => ['exp', 'has_borrow + ' . $money],
            'cash_borrow' => ['exp', 'cash_borrow -' . $money],
            'borrow_times' => ['exp', 'borrow_times + 1']
        ]);

        //发站内信
        $msg_id = db('user_mag')->insertGetId(array(
            'uid' => $uid,
            'title' => '投标成功',
            'msg' => '恭喜您投标成功, 标的号：' . $borrow_id . '，投标金额' . $money . '元' . $msg_tips . '，详情请查看资金记录',
            'send_time' => $_SERVER['REQUEST_TIME']
        ));

        if ($invest_id && $money_flag && $borrow_flag && $msg_id) {

            Db::commit();

            //判断满标 剩余投资金额 = 0 即为满标
            if ($borrow_db->where(['id' => $borrow_id])->value('cash_borrow') == 0) {
                $borrow_db->where(['id' => $borrow_id])->update(array('borrow_status' => 4, 'full_time' => $_SERVER['REQUEST_TIME']));
            }

            //新手投标记录
            //TODO:新手投标奖励
//            $newHandBorrowParams = array(
//                'uid' => $uid,
//                'investor_capital' => $money,
//                'invest_id' => $invest_id,
//                'borrow_id' => $binfo['id'],
//                'borrow_tps' => $binfo['borrow_tps'],
//            );
//            Hook::listen('new_hand_borrow', $newHandBorrowParams);

            //TODO:新手投标奖励
//            $investSendParams = array(
//                'uid' => $uid,
//                'money' => $money,
//                'invest_id' => $invest_id,
//                'borrow_id' => $borrow_id,
//                'duration' => $binfo['borrow_duration']
//            );
//            Hook::listen('invest_send_money', $investSendParams);

            return ['code' => 1, 'msg' => '投标成功！'];
        } else {
            Db::rollback();
            return ['code' => 0, 'msg' => '投标失败，请联系客服！'];
        }
    }


}